package com.simple.car.loader.server.annotation.impl;

import com.simple.car.loader.server.annotation.Loader;
import com.simple.car.loader.server.manager.impl.BeamManager;
import com.simple.car.loader.server.manager.impl.ControllerManager;

import java.lang.reflect.Field;
import java.util.Collection;

public class ControllerImpl {

    public static void init() {
        Collection<Object> values = ControllerManager.getInstance().values();
        values.forEach(o -> {
            Class<?> aClass = o.getClass();
            Field[] fields = aClass.getDeclaredFields();
            for (Field field : fields) {
                Loader loader = field.getDeclaredAnnotation(Loader.class);
                if (loader == null) {
                    continue;
                }
                String value = loader.value();
                if (value.isEmpty()) {
                    value = field.getType().getName();
                }
                Object lookup = BeamManager.getInstance().lookup(value);
                if (lookup == null) {
                    lookup = ControllerManager.getInstance().lookup(value);
                }
                if (lookup == null) {
                    continue;
                }
                boolean accessible = field.isAccessible();
                field.setAccessible(true);
                try {
                    field.set(o, lookup);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } finally {
                    field.setAccessible(accessible);
                }
            }
        });
    }
}
